package impl

import (
	"cn.bupt.byy/monitor/config"
	"context"
	apiV1 "k8s.io/api/core/v1"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type OperationServiceImpl struct {
}

var (
	coreV1 = config.CoreV1()
	appV1  = config.AppsV1()

	namespace = config.GlobalConfig.Byy.Namespace
)

func (s *OperationServiceImpl) Create(c context.Context) {
	clearAffinity()
	coreV1.Services(namespace).Create(c, config.ByySvc, v1.CreateOptions{})
	appV1.Deployments(namespace).Create(c, config.ByyDeploy, v1.CreateOptions{})
}

func (s *OperationServiceImpl) Delete(c context.Context) {
	clearAffinity()
	coreV1.Services(namespace).Delete(c, config.ByySvc.Name, v1.DeleteOptions{})
	appV1.Deployments(namespace).Delete(c, config.ByyDeploy.Name, v1.DeleteOptions{})
}

func (s *OperationServiceImpl) CreateIn(c context.Context, rns []string) {
	setAffinity(rns)
	config.CoreV1().Services(namespace).Create(c, config.ByySvc, v1.CreateOptions{})
	config.AppsV1().Deployments(namespace).Create(c, config.ByyDeploy, v1.CreateOptions{})
}

func clearAffinity() {
	config.ByyDeploy.Spec.Template.Spec.Affinity = nil
}

// 指派调度 指定 pod 调度到 v 中存在的
func setAffinity(v []string) {
	nst := apiV1.NodeSelectorTerm{
		MatchExpressions: []apiV1.NodeSelectorRequirement{
			{
				Key:      "id",
				Operator: "In",
				Values:   v,
			},
		},
		MatchFields: nil,
	}
	aff := &apiV1.Affinity{
		NodeAffinity: &apiV1.NodeAffinity{
			RequiredDuringSchedulingIgnoredDuringExecution:  &apiV1.NodeSelector{NodeSelectorTerms: []apiV1.NodeSelectorTerm{nst}},
			PreferredDuringSchedulingIgnoredDuringExecution: nil,
		},
		PodAffinity:     nil,
		PodAntiAffinity: nil,
	}
	config.ByyDeploy.Spec.Template.Spec.Affinity = aff
}
